import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;


public class SerializationJava {
	private static boolean throughputTest = false;
	private static final int OBJECTS_COUNT = 10_000;
	
	public static void main(String[] args) throws IOException {
		if (args.length < 2) {
			System.err.println("Invalid parameters list. Usage: SerializationJava <remote host> <remote port> ");
			System.exit(1);
		}
		String host = args[0];
		int port = Integer.parseInt(args[1]);
		
		try (Socket socket = new Socket(host, port);){
			ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
			out.flush();
			ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
			long globalBefore = System.currentTimeMillis();
			long delay = 0;
			for (int i = 0; i < OBJECTS_COUNT; i++) {
				SensorData sd = SensorData.generate();
				long localBefore = System.currentTimeMillis();
				out.writeObject(sd);
				if (!throughputTest) {
					byte b = in.readByte();
				}
				long localAfter = System.currentTimeMillis();
				delay += localAfter - localBefore;
			}
			out.flush();
			in.readByte();
			long globalAfter = System.currentTimeMillis();
			if (throughputTest)
				System.out.println("Throughput : " + (double)OBJECTS_COUNT / (globalAfter - globalBefore));
			else 
				System.out.println("Delay : " + ((double)delay / OBJECTS_COUNT));
		} 
	}

}
